package com.weekdo.moviecomic;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

public class WebSimpleAdapter extends SimpleAdapter {
	
	static HashMap<String, Drawable> drawableCache = new HashMap<String, Drawable>();

	public WebSimpleAdapter(Context context,
			List<? extends Map<String, ?>> data, int resource, String[] from,
			int[] to) {
		super(context, data, resource, from, to);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void setViewImage(ImageView v, String imageUrl) {
		((ImageView) v).setImageDrawable(loadImageFromUrl(imageUrl));
	}

	private static Drawable loadImageFromUrl(String imageUrl) {
		if (drawableCache.containsKey(imageUrl))
		{
			return (Drawable) drawableCache.get(imageUrl);
		}
		
		//Log.d("!! LOADING FROM WEB !!", imageUrl);

		try {
			InputStream is = (InputStream) new URL(imageUrl).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			drawableCache.put(imageUrl, d);
			return d;
	 	}catch (Exception e) {
	 		return null;
	 	}
	}

}
